package by.bsu.scs.db.dao;

// Generated 05.03.2011 11:02:55 by Hibernate Tools 3.4.0.CR1

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import by.bsu.scs.model.DisciplineTask;
import by.bsu.scs.model.Task;
import by.bsu.scs.model.User;
import by.bsu.scs.util.db.HibernateUtil;
import by.bsu.scs.util.manager.PropertyManager;

/**
 * Home object for domain model class DisciplineTask.
 * 
 * @see by.bsu.scs.model.DisciplineTask
 * @author Hibernate Tools
 */
public class DisciplineTaskHome {

	private static final Logger LOGGER = Logger
			.getLogger(DisciplineTaskHome.class);
	private static final String GET_DISCIPLINE_TASK_BY_TASK_ID = "getDisciplineTaskByTaskId";
	private static final String TASK_ID = "taskId";

	private Session session = null;
	private Transaction transaction = null;

	public void persist(DisciplineTask transientInstance) {
		LOGGER.info("persisting DisciplineTask instance");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
			LOGGER.info("persist successful");
		} catch (HibernateException e) {
			transaction.rollback();
			LOGGER.error("persist failed", e.getCause());
		}
	}

	public void attachDirty(DisciplineTask instance) {
		LOGGER.info("attaching dirty DisciplineTask instance");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			session.saveOrUpdate(instance);
			transaction.commit();
			LOGGER.info("attach successful");
		} catch (HibernateException e) {
			transaction.rollback();
			LOGGER.error("attach failed", e.getCause());
		}
	}

	@SuppressWarnings("deprecation")
	public void attachClean(DisciplineTask instance) {
		LOGGER.info("attaching clean DisciplineTask instance");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			session.lock(instance, LockMode.NONE);
			transaction.commit();
			LOGGER.info("attach successful");
		} catch (HibernateException e) {
			transaction.rollback();
			LOGGER.error("attach failed", e.getCause());
		}
	}

	public void delete(DisciplineTask persistentInstance) {
		LOGGER.info("deleting DisciplineTask instance");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			session.delete(persistentInstance);
			transaction.commit();
			LOGGER.info("delete successful");
		} catch (HibernateException e) {
			transaction.rollback();
			LOGGER.error("delete failed", e.getCause());
		}
	}

	public DisciplineTask merge(DisciplineTask detachedInstance) {
		LOGGER.info("merging DisciplineTask instance");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			DisciplineTask result = (DisciplineTask) session
					.merge(detachedInstance);
			transaction.commit();
			LOGGER.info("merge successful");
			return result;
		} catch (HibernateException e) {
			transaction.rollback();
			LOGGER.error("merge failed", e.getCause());
			return null;
		}
	}

	public DisciplineTask findById(int id) {
		LOGGER.info("getting DisciplineTask instance with id: " + id);
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			DisciplineTask instance = (DisciplineTask) session.get(
					"by.bsu.scs.model.DisciplineTask", id);
			if (instance == null) {
				LOGGER.info("get successful, no instance found");
			} else {
				LOGGER.info("get successful, instance found");
			}
			transaction.commit();
			return instance;
		} catch (RuntimeException e) {
			transaction.rollback();
			LOGGER.error("get failed", e.getCause());
			return null;
		}
	}

	@SuppressWarnings("rawtypes")
	public List findByExample(DisciplineTask instance) {
		LOGGER.info("finding DisciplineTask instance by example");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();
			Example example = Example.create(instance).excludeZeroes();
			List results = session
					.createCriteria("by.bsu.scs.model.DisciplineTask")
					.add(example).list();
			LOGGER.info("find by example successful, result size: "
					+ results.size());
			transaction.commit();
			return results;
		} catch (RuntimeException e) {
			transaction.rollback();
			LOGGER.error("find by example failed", e.getCause());
			return null;
		}
	}

	// ***************** Manually created methods ******************

	public DisciplineTask getDisciplineTaskByTaskId(int taskId) {
		Session session = HibernateUtil.openCurrentSession();
		Transaction transaction = null;
		DisciplineTask disciplineTask = null;
		try {
			transaction = session.beginTransaction();
			disciplineTask = (DisciplineTask) session
					.getNamedQuery(GET_DISCIPLINE_TASK_BY_TASK_ID)
					.setInteger(TASK_ID, taskId).list().get(0);
			transaction.commit();
			LOGGER.info("find successful");
		} catch (HibernateException e) {
			if (transaction != null) {
				transaction.rollback();
			}
			LOGGER.error("find failed", e.getCause());
		}
		return disciplineTask;
	}

	@SuppressWarnings("unchecked")
	public List<Task> getTasksByStudentAndDisciplineIdSQL(User student,
			int disciplineId) {
		LOGGER.info("finding tasks by student, discipline");
		session = HibernateUtil.openCurrentSession();
		try {
			transaction = session.beginTransaction();

			String sql = PropertyManager
					.getInstance()
					.getProperty(
							PropertyManager.TASK_BY_STUDENT_ID_AND_DISCIPLINE_ID);

			Object[] params = { student.getUserId(), disciplineId };
			MessageFormat messageToFormat = new MessageFormat(sql);
			sql = messageToFormat.format(params);

			List<Integer> results = session.createSQLQuery(sql).list();
			
			LOGGER.info("find successful, result size: " + results.size());
			transaction.commit();

			System.out.println("************");
			return parseTaskData(results);
		} catch (RuntimeException e) {
			transaction.rollback();
			LOGGER.error("find failed", e.getCause());
			return null;
		}
	}

	private List<Task> parseTaskData(List<Integer> results) {
		List<Task> taskList = new ArrayList<Task>();
		for (Integer i : results) {
			//Object[] taskData = (Object[]) o;
			Task task = new TaskHome().findById(i);
			taskList.add(task);
		}
		return taskList;
	}

}
